import ajax from "./request";
const QQMapWX = require('./qqmap-wx-jssdk.min')
const app = getApp()
const showToast = (title, icon = 'none', duration = 2000) => new Promise((resolve, reject) => wx.showToast({ title, duration, icon, success: () => setTimeout(() => resolve(), duration), fail: () => reject() }));

/**
   * 开启设置页面
   */
const openSetting = () => {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title: '温馨提示',
      content: '请开启系统定位并授权位置信息，以提供更好的服务',
      confirmText: '去授权',
      success: (res) => {
        if (!res.confirm) return resolve(null)
        wx.openSetting({ success: (res) => resolve(res.authSetting) })
      }
    });
  })
}

/**
 * 查看授权
 */
const getSetting = () => {
  return new Promise((resolve, reject) => {
    wx.getSetting({ success: (res) => resolve(res.authSetting) })
  })
}


/**
 * 获取腾讯地图对象
 */
const getQQMap = () => new QQMapWX({ key: app.globalData.qq_maps_key })



/**
 * 获取定位信息 返回省市区 区code  经度纬度
 */
const getLocationQQMap = () => {
  const qqmapsdk = getQQMap();
  return new Promise((resolve, reject) => {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        qqmapsdk.reverseGeocoder({
          location: { latitude: res.latitude, longitude: res.longitude },
          success: (res) => {
            const { ad_info, address } = res.result;
            ad_info.address = address
            ad_info.type = true
            resolve(ad_info)
            app.globalData.locatingInfo = ad_info
          },
          fail: (err) => (app.globalData.locatingInfo = null, reject(err))
        });
      },
      fail: async (err) => {
        const setting = await getSetting()
        if (setting['scope.userLocation']) return
        app.globalData.locatingInfo = null
        resolve({
          type: false,
          adcode: "330106",
          address: "浙江省杭州市西湖区省府路8号",
          city: "杭州市",
          city_code: "156330100",
          district: "西湖区",
          location: { lat: 30.26548, lng: 120.15335 },
          name: "中国,浙江省,杭州市,西湖区",
          nation: "中国",
          nation_code: "156",
          province: "浙江省"
        });
        wx.showModal({
          title: '定位授权',
          content: '请前往手机设置, 开通微信定位授权',
          showCancel: false
        });
      }
    })
  })
}

/**
 * 获取经度纬度
 */
const getLocation = () => {
  return new Promise((resolve, reject) => {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => resolve(res),
      fail: (err) => {
        console.log(err)
        reject()
        wx.showModal({
          title: '定位授权',
          content: '请前往手机设置, 开通微信定位授权',
          showCancel: false
        });
      }
    })
  })
}

/**
 * 获取地址
 */
const chooseLocation = () => {
  const qqmapsdk = getQQMap();
  return new Promise((resolve, reject) => {
    wx.chooseLocation({
      complete: (location) => {
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: location.latitude,
            longitude: location.longitude
          },
          success: (res) => {
            console.log('chooseLocation', res)
            const { ad_info, address_component, address_reference, location } = res.result
            resolve({
              province: ad_info.province,
              city: ad_info.city,
              county: ad_info.district,
              town: address_reference.town.title, // 街道
              address: address_component.street_number,
              latitude: ad_info.location.lat,
              longitude: ad_info.location.lng
            })
          },
          fail: (err) => reject(err)
        })
      },
      fail: (err) => reject(err)
    })
  })

}
/**
 * 根据地址 打开地图
 */
const openMmap = (location, type = 1) => {
  console.log(location, type)
  if (type == 2) {
    return wx.openLocation({
      latitude: location.lat - 0,
      longitude: location.lng - 0,
      address: location.address,
      scale: 18
    })
  }
  const qqmapsdk = getQQMap();
  qqmapsdk.geocoder({
    address: location,
    success: (res) => {
      var result = res.result;
      wx.openLocation({
        latitude: result.location.lat,
        longitude: result.location.lng,
        address: location,
        scale: 18
      })
    },
    fail: (err) => showToast(err.message)
  })
}

/**
 * 计算底部安全距离
 */
const getSafeArea = () => {
  const system = wx.getSystemInfoSync()
  return system.safeArea && system.safeArea.bottom && system.screenHeight ? system.screenHeight - system.safeArea.bottom : 0;
}


/**
 * 计算标题栏高度
 */
const getHeadlineHeight = () => {
  const system = wx.getSystemInfoSync()
  let custom = wx.getMenuButtonBoundingClientRect();
  return custom.bottom + custom.top - system.statusBarHeight
}

/**
 * 拨打电话
 * @param {手机号} phoneNumber 
 */

const makePhoneCall = (phoneNumber) => wx.makePhoneCall({ phoneNumber })


/**
 * 从客户端会话选择文件
 */
const chooseMessageFile = (data) => {
  const options = {
    type: data?.type || 'file',
    count: data?.count || 1,
    extension: data?.extension || ['xlsx', 'csv'],
  }
  return new Promise(function (resolve, reject) {
    wx.chooseMessageFile({
      ...options,
      success: (res) => resolve(res),
      fail: () => reject()
    })
  })
}

/**
 * 相册选择
 */
const chooseImage = (type = "image") => {
  return new Promise((resolve, reject) => {
    wx.chooseMedia({
      count: 1,
      mediaType: [type == 'video' ? 'video' : 'image'],
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      maxDuration: 60,
      camera: 'back',
      success: (res) => resolve(res.tempFiles[0].tempFilePath),
      fail: () => reject()
    })
  });
}


/**
  * 统一 pdf 文件上传
  */
const uploadFilePDF = (options) => {
  return new Promise((resolve, reject) => {
    wx.chooseMessageFile({
      type: 'file',
      count: 1,
      extension: options?.extension || ['pdf'], //可上传格式
      success: async (res) => {
        const file = res.tempFiles.shift()
        const fileRes = await ajax.uploadFile({ filePath: file.path, name: 'file' }, '/common/uploadFile2Cos');
        fileRes.code == 200 ? resolve(Object.assign(fileRes, file)) : reject(fileRes)
      },
      fail: (err) => reject(err)
    })
  })
}

/**
 * 正则对象
 */
const regExp = {
  card: /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
  phone: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
  chinese: /^[\u4E00-\u9FA3]{2,}$/
}

const windowSearch = (text) => {
  const str = unescape(text)
  return str ? JSON.parse('{"' + str.replace(/=/g, '":"').replace(/&/g, '","') + '"}') : null;
}

/**
 * 获取 小程序二维码
 * @param {page: 路径, id: 详情ID, shareId: 分享人ID} formData 
 */
const getQrCode = async (formData) => {
  const res = await ajax.post('/wx/appletQrCode/add', formData);
  const buffer = wx.base64ToArrayBuffer(res.msg)
  return new Promise((resolve, reject) => {
    wx.getFileSystemManager().writeFile({
      filePath: `${wx.env.USER_DATA_PATH}/tmp_base64src`,
      data: buffer,
      success: () => resolve(`${wx.env.USER_DATA_PATH}/tmp_base64src`),
      fail: (err) => (reject(err), ajax.showToast("获取二维码失败"))
    })
  })
}
/**
 * 获取元素宽度
 */
const getElement = (id, _this) => {
  return new Promise((resolve, reject) => wx.createSelectorQuery().in(_this).select(id).boundingClientRect((rect) => !rect ? reject() : resolve(rect)).exec())
}

export default {
  getSetting, openSetting,
  getQQMap,
  getLocationQQMap,
  getLocation,
  chooseLocation,
  getSafeArea,
  getHeadlineHeight,
  openMmap,
  makePhoneCall,
  chooseMessageFile,
  chooseImage,
  uploadFilePDF,
  regExp,
  windowSearch,
  getQrCode,
  getElement
};